import 'date_time_utils.dart';

class ListToMapUtils {
  static int sortNameFirst<T>(T a, T b, String getName(T t)) {
    String aName = getName(a);
    String bName = getName(b);
    if (aName.length > 0 && bName.length > 0) {
      return aName[0].toUpperCase().compareTo(bName[0].toUpperCase());
    } else if (aName.length == 0) {
      return 1;
    } else {
      return 0;
    }
  }

  static int sortName<T>(T a, T b, String getName(T t)) {
    String aName = getName(a);
    String bName = getName(b);
    if (aName.length > 0 && bName.length > 0) {
      return aName.toUpperCase().compareTo(bName.toUpperCase());
    } else if (aName.length == 0) {
      return 1;
    } else {
      return 0;
    }
  }

  static int sortIssuesAt<T>(
      T a, T b, String getIssuedAt(T t), int getId(T t)) {
    final aTime =
        DateTimeUtils.toDateTime(getIssuedAt(a), 'yyyy-MM-dd HH:mm:ss');
    final bTime =
        DateTimeUtils.toDateTime(getIssuedAt(b), 'yyyy-MM-dd HH:mm:ss');
    if (DateTimeUtils.formatDateTime(aTime, 'yyyy-MM-dd') ==
        DateTimeUtils.formatDateTime(bTime, 'yyyy-MM-dd')) {
      return getId(a).compareTo(getId(b));
    }
    return getIssuedAt(a).compareTo(getIssuedAt(b));
  }

  static String groupFirstName<T>(T a, String getName(T t),
      [String other = '']) {
    return getName(a) != null && getName(a).length > 0
        ? getName(a)[0].toUpperCase()
        : other;
  }

  static String groupMonth<T>(T a, String getTimeAt(T t)) {
    DateTime start = DateTimeUtils.toDateTime(getTimeAt(a), 'yyyy-MM-dd');
    String month = DateTimeUtils.formatDateTime(start, 'MMM');
    return month;
  }

  static bool favoriteBefore<T>(
      Map<String, List<T>> map, T b, int getFavorite(T b)) {
    if (getFavorite(b) == 1) {
      if (map['Favourites'] == null) {
        map['Favourites'] = [b];
      } else {
        map['Favourites'].add(b);
      }
      return true;
    } else if (map['Favourites'] == null) {
      map['Favourites'] = [];
    }
    return false;
  }

  static int sortPayAmount<T>(
      T a, T b, int getFavorite(T t), num getAmount(T t)) {
    int aF = getFavorite(a);
    int bF = getFavorite(b);
    if ((aF == 1 && bF == 1) || (aF == 0 && bF == 0))
      return (getAmount(b)).abs().compareTo((getAmount(a)).abs());
    if (aF == 1) {
      return 0;
    }
    return 1;
  }
}
